package com.ls.markt.controller.superLeague;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.markt.model.superLeague.SuperLeague;
import com.ls.markt.service.admin.ClubService;
import com.ls.markt.service.admin.EnumManageItemService;
import com.ls.markt.service.superLeague.SuperLeagueService;
import com.ls.markt.util.WebResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 中超联赛控制器
 */
@RestController
@RequestMapping("/super")
public class SuperController {

    @Resource
    private SuperLeagueService superLeagueService;

    @Resource
    private EnumManageItemService enumManageItemService;

    @Resource
    private ClubService clubService;

    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("superLeague/super/index");
    }

    @PostMapping("/list")
    public JSONObject list(@RequestParam(value="page",required=false,defaultValue="1")int page,
                           @RequestParam(value="rows",required=false,defaultValue="10")int rows){
        PageRequest pageRequest = PageRequest.of(page-1,rows);
        Page<SuperLeague> leagues = superLeagueService.listSuperLeagues(pageRequest);
        JSONArray jsonArray = new JSONArray();
        for (SuperLeague league: leagues.getContent()){
            JSONObject json = (JSONObject) JSONObject.toJSON(league);
            json.put("seasonId",enumManageItemService.getNameById(league.getSeasonId()));
            json.put("clubId",clubService.getClubName(league.getClubId()));
            jsonArray.add(json);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows",jsonArray);
        jsonObject.put("total",leagues.getTotalElements());
        return jsonObject;
    }

    @GetMapping("/add")
    public ModelAndView add(){
        return new ModelAndView("superLeague/super/add");
    }

    @RequestMapping("edit/{id}")
    public ModelAndView edit(@PathVariable("id")Long id){
        SuperLeague superLeague = superLeagueService.getById(id);
//        model.addAttribute("superLeague",superLeague);
        return new ModelAndView("superLeague/super/edit","superLeague",superLeague);
    }

    @PostMapping("/save")
    public JSONObject save(SuperLeague superLeague){
        superLeagueService.save(superLeague);
        return WebResult.success();
    }

    @RequestMapping("/doDelete")
    public JSONObject doDelete(@RequestParam Long[] ids){
        superLeagueService.removeSuperLeagues(ids);
        return WebResult.success();
    }

}
